package com.ewing.busi.api.login.service;

import java.util.Date;

import javax.annotation.Resource;

import org.apache.commons.codec.digest.DigestUtils;
import org.apache.commons.lang.StringUtils;
import org.apache.commons.lang.Validate;
import org.apache.log4j.Logger;
import org.springframework.stereotype.Repository;

import com.ewing.busi.api.login.dto.SmsAuthorizeReq;
import com.ewing.busi.customer.constants.AccountThirdPlatform;
import com.ewing.busi.customer.constants.Sex;
import com.ewing.busi.customer.model.Customer;
import com.ewing.busi.customer.model.CustomerThirdAccount;
import com.ewing.busi.customer.service.CustomerService;
import com.ewing.busi.customer.service.CustomerThirdAccountService;
import com.ewing.common.constants.AjaxRespCode;
import com.ewing.common.constants.IsEff;
import com.ewing.common.exception.BusinessException;
import com.ewing.core.auth.HttpSessionUtils;
import com.ewing.core.auth.SmsAuthCodeCache;
import com.ewing.core.auth.helper.SmsAuthCodeCacheHelper;
import com.ewing.core.jdbc.BaseDao;
import com.ewing.core.redis.RedisException;
import com.ewing.extranal.sms.service.SmsApiService;
import com.ewing.utils.BizGenerator;
import com.ewing.utils.IntegerUtils;
import com.google.common.base.Charsets;
import com.taobao.api.ApiException;

@Repository("smsAuthorizeService")
public class SmsAuthorizeService {

	private static Logger logger = Logger.getLogger(SmsAuthorizeService.class);

	@Resource
	private BaseDao baseDao;
	@Resource
	private CustomerThirdAccountService customerThirdAccountService;
	@Resource
	private CustomerService customerService;

	public boolean authCode(SmsAuthorizeReq req) {
		Validate.notNull(req.getPhone(), "手机不能为空");
		Validate.notNull(req.getPass(), "密码不能为空");

		Customer customer = null;
		CustomerThirdAccount thirdAccount = null;

		// 验证码不为空，说明是第一次注册/找回密码
		if (StringUtils.isNotEmpty(req.getCode())) {// 注册
			Validate.notNull(req.getConfirmPass(), "确认密码不能为空");

			SmsAuthCodeCache cache = SmsAuthCodeCacheHelper.getCache(req.getPhone());
			if (!SmsAuthCodeCacheHelper.isValidCache(cache) || !StringUtils.equals(cache.getCode(), req.getCode())){
				return false;
			}
			
			//验证码缓存，验证后的操作
			SmsAuthCodeCacheHelper.authAuth(cache);
			// 密码和确认密码不一致的情况，不能通过
			if (!StringUtils.equals(req.getPass(), req.getConfirmPass())) {
				return false;
			}else{
			  SmsAuthCodeCacheHelper.del(req.getPhone());
			}

			customer = null;
			thirdAccount = customerThirdAccountService.findByUserIdAndPlatId(
					req.getPhone(), AccountThirdPlatform.PHONE.getValue());
			if (null == thirdAccount) {
				customer = new Customer();
				customer.setName(StringUtils.substring(
						BizGenerator.generateUUID(), 0, 9));
				customer.setPassword(DigestUtils.md5Hex(req.getPass().getBytes(
						Charsets.UTF_8)));
				customer.setHeadIcon("");
				customer.setPhone(req.getPhone());
				customer.setSex(Sex.MAN.getValue());
				customer.setIseff(IsEff.EFFECTIVE.getValue());
				customer.setCreateTime(new Date());
				baseDao.save(customer);

				thirdAccount = new CustomerThirdAccount();
				thirdAccount.setCustomerId(customer.getId());
				thirdAccount.setThirdPlatform(AccountThirdPlatform.PHONE
						.getValue());
				thirdAccount.setHeadIcon("");
				thirdAccount.setNickName(customer.getName());
				thirdAccount.setUserId(req.getPhone());
				thirdAccount.setCreateTime(new Date());
				baseDao.save(thirdAccount);
			}else if(IntegerUtils.equals(req.getLogin(), 2)){//找回密码
			  customer = customerService.queryById(thirdAccount.getCustomerId());
			  if(null == customer){
			    throw new BusinessException(AjaxRespCode.SMS_WITHOUT_LOGIN_MSG.code, "找不到注册信息，请注册");
			  }
			  
			  //修改密码并进行更新
			  customer.setPassword(DigestUtils.md5Hex(req.getPass().getBytes(
                  Charsets.UTF_8)));
			  customerService.update(customer);
			}
		} else {// 登陆
			thirdAccount = customerThirdAccountService.findByUserIdAndPlatId(
					req.getPhone(), AccountThirdPlatform.PHONE.getValue());
			if (null == thirdAccount) {
				return false;
			}
			customer = customerService.queryById(thirdAccount.getCustomerId());
			if (null == customer
					|| !StringUtils.equals(
							DigestUtils.md5Hex(req.getPass().getBytes(
									Charsets.UTF_8)), customer.getPassword())) {
				return false;
			}
		}

		// 设置登陆session
		try {
			HttpSessionUtils.setSmsSessionUserDetails(customer,
					thirdAccount.getCustomerId());
		} catch (RedisException e) {
			logger.error(e.getMessage(), e);
			return false;
		}

		return true;
	}

	public boolean isCustomer(SmsAuthorizeReq req) {
		Validate.notNull(req, "入参不能为空");
		Validate.notNull(req.getPhone(), "手机号码为空");

		CustomerThirdAccount thirdAccount = customerThirdAccountService
				.findByUserIdAndPlatId(req.getPhone(),
						AccountThirdPlatform.PHONE.getValue());
		if (null == thirdAccount) {
			return false;
		}
		Customer customer = customerService.queryById(thirdAccount
				.getCustomerId());
		if (null == customer) {
			return false;
		}

		return true;
	}

	/**
	 * 发送手机短信验证码
	 * @param req
	 * @return
	 */
	public boolean sendAuthCode(SmsAuthorizeReq req) {
		Validate.notNull(req, "入参不能为空");
		Validate.notNull(req.getPhone(), "手机号码不能为空");
		
		SmsAuthCodeCache cache = SmsAuthCodeCacheHelper.getCache(req.getPhone());
		if(SmsAuthCodeCacheHelper.isValidCache(cache)){
		  throw new BusinessException(AjaxRespCode.SMS_VALID_AUTH_CODE);
		}
		
		String code =BizGenerator.generateRandomCode(true, 6);
		if(!SmsAuthCodeCacheHelper.set(req.getPhone(), code)){
		  return false;
		}
		
		try {
			SmsApiService.sendAuthSms(req.getPhone(), code);
		} catch (ApiException e) {
			logger.error(e.getMessage(), e);
			return false;
		}
		
		return true;
	}

}
